package com.elitel.common.delegate;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.elitel.common.result.ResultType;
import com.elitel.common.result.SrvResult;

public class ControllerDelegate<X> implements InvocationHandler {

    private Log log = LogFactory.getLog(ControllerDelegate.class);
    private Object target;

    public Object call(Object target) {
        this.target = target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),
                target.getClass().getInterfaces(), this);
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        if (log.isDebugEnabled()) {
            log.debug("方法[" + method.getName() + "]调用开始......");
        }
        SrvResult<X> sr = new SrvResult<X>();
        try {

            // 登录认证
            // before method
            Object result = method.invoke(target, args);
            // after method
            sr.setResultType(ResultType.Ok.getValue());
            sr.setValue((X) result);
        } catch (Throwable t) {

            // after exception
            sr.setResultType(ResultType.Exception.getValue());
            sr.setErrorMsg(t.getMessage());
            StringBuffer sb = new StringBuffer();
            for (StackTraceElement element : t.getStackTrace()) {
                sb.append("\r\n\t" + element);
            }
            sr.setStackMsg(sb.toString());

            if (log.isDebugEnabled()) {
                log.debug("方法[" + method.getName() + "]调用异常：", t);
            }
        } finally {
            if (log.isDebugEnabled()) {
                log.debug("方法[" + method.getName() + "]调用结束......");
            }
        }
        return sr;
    }
}
